﻿namespace AntdUI_HamburgerMenuTabs.Pages.Tools
{
    public partial class RandomCode : UserControl
    {
        public RandomCode()
        {
            InitializeComponent();

            checkUpper.Checked = true;
            checkNum.Checked = true;

            inputLen.PrefixClick += (s, e) =>
            {
                inputLen.Value = 8;
            };

            inputCnt.Value = 10;

            inputCnt.PrefixClick += (s, e) =>
            {
                inputCnt.Value = 10;
            };

            btnGenerate.Click += (s, e) => GenerateRandomCode();
        }

        private void GenerateRandomCode()
        {
            HashSet<string> res = [];
            DateTime dtStart = DateTime.Now;
            int timesTotal = 0;
            int timesIgnore = 0;
            string msg = "";

            Common.RandomCode rndCode = new(checkUpper.Checked, checkLower.Checked, checkNum.Checked, checkSpecial.Checked);

            if (rndCode.GetCharsLength() == 0) return;

            if (inputCnt.Value > rndCode.GetMaxCount())
            {
                msg = $"编码池上限为 {rndCode.GetMaxCount()} ，当前待生成编码个数已超出上限！";
                ParentForm!.AntModalShowWarn(msg);
                return;
            }

            inputRes.Clear();

            gridPanelMain.Spin((config) =>
            {
                res = rndCode.GetUniqueCodes((int)inputLen.Value, (int)inputCnt.Value, out timesTotal, out timesIgnore);

                if (inputCnt.Value <= 1000)
                {
                    inputRes.Text = string.Join(Environment.NewLine, res);
                }
                else
                {
                    inputRes.Text = "数据量太大，取消显示。";
                }
            }, () =>
            {
                msg = $"生成完毕。\r\n耗时 {(int)(DateTime.Now - dtStart).TotalMilliseconds} 毫秒。\r\n计划生成 {(int)inputCnt.Value} 个编码，实际生成 {res.Count} 个编码。\r\n合计尝试生成 {timesTotal} 次，共丢弃 {timesIgnore} 个重复编码，重复概率为 {Math.Round(timesIgnore * 1.0 / timesTotal, 8)}。";
                
                AntdUI.Notification.success(ParentForm!, Common.App.AppName, msg, AntdUI.TAlignFrom.Bottom, Font, 5);
                
                res.Clear();
            });
        }
    }
}